<template>
  <div class="recognition-detail-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>识别记录详情</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-descriptions title="基本信息" :column="2" border>
              <el-descriptions-item label="记录ID">{{
                recordInfo.id
              }}</el-descriptions-item>
              <el-descriptions-item label="用户账号">{{
                recordInfo.username
              }}</el-descriptions-item>
              <el-descriptions-item label="用户ID">{{
                recordInfo.user_id
              }}</el-descriptions-item>
              <el-descriptions-item label="真实姓名">{{
                recordInfo.real_name || "未知"
              }}</el-descriptions-item>
              <el-descriptions-item label="识别类型">
                <el-tag :type="getTypeTagType(recordInfo.recognition_type)">
                  {{ getRecognitionTypeName(recordInfo.recognition_type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="识别结果">
                <el-tag
                  :type="
                    recordInfo.recognition_result === 'success'
                      ? 'success'
                      : 'danger'
                  "
                >
                  {{
                    recordInfo.recognition_result === "success"
                      ? "成功"
                      : "失败"
                  }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="识别率"
                >{{ recordInfo.success_rate }}%</el-descriptions-item
              >
              <el-descriptions-item label="设备信息">{{
                recordInfo.device_info
              }}</el-descriptions-item>
              <el-descriptions-item label="IP地址">{{
                recordInfo.ip_address
              }}</el-descriptions-item>
              <el-descriptions-item label="地理位置">{{
                recordInfo.location
              }}</el-descriptions-item>
              <el-descriptions-item label="识别时间">{{
                recordInfo.created_at
              }}</el-descriptions-item>

              <template v-if="recordInfo.recognition_data">
                <el-descriptions-item
                  label="识别耗时"
                  v-if="recordInfo.recognition_data.verification_time"
                >
                  {{ recordInfo.recognition_data.verification_time }}
                </el-descriptions-item>
                <el-descriptions-item
                  label="置信度"
                  v-if="
                    recordInfo.recognition_data.confidence_score !== undefined
                  "
                >
                  {{
                    (
                      recordInfo.recognition_data.confidence_score * 100
                    ).toFixed(2)
                  }}%
                </el-descriptions-item>
                <el-descriptions-item
                  label="特征点检测"
                  v-if="
                    recordInfo.recognition_data.face_landmarks !== undefined
                  "
                >
                  <el-tag
                    :type="
                      recordInfo.recognition_data.face_landmarks
                        ? 'success'
                        : 'danger'
                    "
                  >
                    {{
                      recordInfo.recognition_data.face_landmarks
                        ? "成功"
                        : "失败"
                    }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item
                  label="身份验证"
                  v-if="
                    recordInfo.recognition_data.identity_verified !== undefined
                  "
                >
                  <el-tag
                    :type="
                      recordInfo.recognition_data.identity_verified
                        ? 'success'
                        : 'danger'
                    "
                  >
                    {{
                      recordInfo.recognition_data.identity_verified
                        ? "已验证"
                        : "未验证"
                    }}
                  </el-tag>
                </el-descriptions-item>
              </template>
            </el-descriptions>

            <!-- 展示识别结果内容 -->
            <div
              v-if="
                recordInfo.recognition_data &&
                recordInfo.recognition_data.results &&
                recordInfo.recognition_data.results.length > 0
              "
              class="result-box"
            >
              <p class="image-title">识别内容</p>
              <ul class="result-list">
                <li
                  v-for="(item, index) in recordInfo.recognition_data.results"
                  :key="index"
                >
                  <div class="result-item">
                    <p v-if="item.type_text" class="result-subject">
                      {{ item.type_text }}
                    </p>
                    <p class="result-subject">{{ item.subject }}</p>
                    <p v-if="item.optionA" class="result-subject">
                      答案1:{{ item.optionA }}
                    </p>
                    <p v-if="item.optionB" class="result-subject">
                      答案2:{{ item.optionB }}
                    </p>
                    <p v-if="item.optionC" class="result-subject">
                      答案3:{{ item.optionC }}
                    </p>
                    <p v-if="item.optionD" class="result-subject">
                      答案4:{{ item.optionD }}
                    </p>
                    <!-- <p class="result-similarity">
                      相似度：{{ (item.similarity * 100).toFixed(2) }}%
                    </p> -->
                  </div>
                </li>
              </ul>
            </div>
          </el-col>

          <el-col
            :span="8"
            v-if="recordInfo.photo_url || recordInfo.recognition_image"
          >
            <div class="image-box">
              <p class="image-title">识别图像</p>
              <div class="image-container">
                <el-image
                  :src="
                    getDirectUrl(
                      recordInfo.photo_url || recordInfo.recognition_image
                    )
                  "
                  class="preview-image"
                  :preview-src-list="[
                    getDirectUrl(
                      recordInfo.photo_url || recordInfo.recognition_image
                    ),
                  ]"
                  preview-teleported
                  fit="contain"
                  @error="handleImageError"
                />
              </div>
            </div>
          </el-col>
        </el-row>

        <div class="action-box">
          <el-button type="danger" @click="handleDelete">删除记录</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import {
  getRecognitionDetail,
  deleteRecognition,
} from "@/api/recognition-records";

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const recordInfo = ref({});
const recordId = ref(parseInt(route.params.id) || 0);

// 获取记录详情
const getDetail = async () => {
  if (!recordId.value) {
    ElMessage.error("记录ID不能为空");
    return;
  }

  loading.value = true;
  try {
    const res = await getRecognitionDetail(recordId.value);
    if (res.code === 0) {
      recordInfo.value = res.data;
    } else {
      ElMessage.error(res.message || "获取记录详情失败");
    }
  } catch (error) {
    console.error("获取记录详情失败", error);
    ElMessage.error("获取记录详情失败");
  } finally {
    loading.value = false;
  }
};

// 返回列表页
const goBack = () => {
  router.push("/recognition/list");
};

// 删除记录
const handleDelete = () => {
  ElMessageBox.confirm(`确认要删除该识别记录吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteRecognition(recordId.value);
        if (res.code === 0) {
          ElMessage.success("删除成功");
          goBack();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取识别类型名称
const getRecognitionTypeName = (type) => {
  const typeMap = {
    face: "人脸识别",
    id_card: "身份证",
    drive_license: "驾驶证",
  };
  return typeMap[type] || "未知";
};

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    face: "primary",
    id_card: "success",
    drive_license: "warning",
  };
  return typeMap[type] || "";
};

// 打开下载URL
const openDownloadUrl = (url) => {
  if (!url) return;

  // 确保URL使用https
  if (url.startsWith("http:")) {
    url = url.replace("http:", "https:");
  } else if (!url.startsWith("http")) {
    url = "https://" + url;
  }

  // 打开新标签页
  window.open(url, "_blank");
  console.log("打开图片链接:", url);
};

// 获取直接URL
const getDirectUrl = (url) => {
  if (!url) return "";

  // 确保URL使用https
  if (url.startsWith("http:")) {
    url = url.replace("http:", "https:");
  } else if (!url.startsWith("http")) {
    url = "https://" + url;
  }

  return url;
};

// 打开直接URL
const openDirectUrl = (url) => {
  if (!url) return;
  window.open(getDirectUrl(url), "_blank");
};

// 处理图片错误
const handleImageError = (event) => {
  // 设置一个默认的加载失败图片（如果资源不可用，则显示一个简单的图标）
  event.target.style.display = "none";
  // 显示一个错误提示或备用按钮
  const container = event.target.parentElement;
  if (container) {
    const errorIcon = document.createElement("div");
    errorIcon.className = "error-placeholder";
    errorIcon.innerHTML =
      '<i class="el-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M160 224a32 32 0 0 0-32 32v512a32 32 0 0 0 32 32h704a32 32 0 0 0 32-32V256a32 32 0 0 0-32-32H160zm352 64h160v96H512V288zm-192 96h128v64H320v-64zM224 416h576v288H224V416z"></path></svg></i>';
    errorIcon.style.cursor = "pointer";
    errorIcon.onclick = () =>
      openDirectUrl(
        recordInfo.value.photo_url || recordInfo.value.recognition_image
      );
    container.appendChild(errorIcon);
  }
};

onMounted(() => {
  getDetail();
});
</script>

<style scoped>
.recognition-detail-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.image-box {
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
  text-align: center;
}

.image-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #606266;
}

.image-container {
  position: relative;
  width: 100%;
  height: 300px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  cursor: pointer;
}

.error-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.action-box {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 表单样式优化 */
:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

.el-tag {
  font-weight: 500;
}

.result-box {
  margin-top: 20px;
  padding: 12px;
  background: #ffffff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
}

.result-list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.result-item {
  margin-bottom: 12px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.result-subject {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.result-similarity {
  font-size: 13px;
  color: #909399;
}
</style>
